<template>
    <div class="achievementDetail common">
        <innerCommon 
            :location="location"
        >
            <template slot="left">
                <span>{{type==0?'学生':''}}成绩列表</span>
                <selectDate @changTime="changTime" v-if="type==0&&info!='onePlusExam'"></selectDate>
                <a-input-search 
                    class="inputStyle" 
                    placeholder="搜索"  
                    enter-button 
                    style="margin-left:10px;"
                    @search="onSearch" />
            </template>
            <template slot="right"> 
                <a-button type="primary" @click="openUploadBox()" v-if="type==1||info=='onePlusExam'">成绩录入</a-button>
                <download 
                    v-if="info=='onePlusExam'"
                    :name="'导出成绩表'"
                    :methods="'post'"
                    :api="'manage/onePlusXRecord/exportRecord'"
                    :fileName="'成绩表.xls'"
                    :formData="{'type':this.type,'activityId':activityId}"
                    style="margin-left:10px"
                ></download>
                <download 
                    v-else
                    :name="'导出成绩表'"
                    :api="'manage/record/exportCourseRecord'"
                    :fileName="'成绩表.xls'"
                    :formData="{'courseId':this.searchInfo.courseId,'type':this.type}"
                    style="margin-left:10px"
                ></download>
                <a-button type="primary" style="margin-left:10px;" v-if="list.length>0" :disabled="clickFlag" @click="generateCourseCert()">批量生成证书</a-button>
                <a-button type="primary" style="margin-left:10px;" @click="openTemplate()">{{imgSrc?'修改证书模板':'上传证书模板'}}</a-button>
                <a-button type="primary" style="margin-left:10px;" @click="returnBack()">返回</a-button>
            </template>
            <div slot="table">
                <a-table 
                    size="middle"
                    :columns="columns" 
                    :data-source="list" 
                    :pagination="pagination"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                    :rowKey="record=>record.id"
                    @change="changePage"
                    :locale="{'emptyText': '暂无数据'}"
                    bordered>
                    <div slot="score" slot-scope="index,record">
                        <a-tag v-if="record.examType!=1">理论{{record.theoryScore}}</a-tag>
                        <a-tag v-if="record.examType!=0">实操{{record.operationScore}}</a-tag>
                    </div>
                    <div slot="passed" slot-scope="index,record">
                        <span v-if='record.passed==1' style="color:green">是</span>
                        <span v-else style="color:red">否</span>
                    </div>
                    <div slot="action" slot-scope="index,record"  class="tableAction">
                        <template v-if="record.passed==0&&info!='onePlusExam'">
                            <span v-if="record.resetted==0" @click="reviewTest(record.id,record.realname)">
                                重新考试
                            </span>
                            <span v-else style="color:#999">
                                重新考试
                            </span>
                        </template>
                        <template v-if="!record.certificate">
                            <span v-if="record.passed==1" @click.once="generateCourseCert(record.id)">证书生成</span>
                        </template>
                        <span v-if="record.passed==1&&record.certificate" @click="previewCert(record.certificate.imgUrl,record.name)">证书预览</span>
                        <confirmBox
                            v-if="record.passed==1&&record.certificate"
                            @handleOk="deleteCert(record)"
                            :typeName="'删除'"
                            :noticeInfo="record.realname"
                            :noticeType="'的证书'"
                        ></confirmBox>
                        <confirmBox
                            v-if="!record.certificate&&type==1"
                            @handleOk="deleteRecord(record)"
                            :typeName="'删除'"
                            :noticeInfo="record.realname"
                            :noticeType="'的成绩'"
                        ></confirmBox>
                        <span v-if="type==0&&info!='onePlusExam'"></span>
                        <span @click="editRecord(record)" v-else>修改</span>
                    </div>
                </a-table>
                 <div style="margin-top:10px">
                     <!-- <a-button  style="margin-right:10px" >
                         <a-checkbox  @change="checkAll($event)" >全选</a-checkbox>
                     </a-button> -->
                    
                    <!-- <a-button type="primary" style="margin-right:10px" >取消全选</a-button>  -->
                    <a-button v-if="type==1&&info=='onePlusExam'" :disabled="this.list.length===0?true:false" type="primary"  style="margin-right:10px" @click="batchDelResult()">批量删除成绩</a-button>
                    <a-button   :disabled="this.list.length===0?true:false" type="primary" @click="batchDelCert()">批量删除证书</a-button>
                 </div>
            </div>
        </innerCommon>
        <a-modal
            :title="imgSrc?'修改证书模块':'上传证书模块'"
            :visible="templateModal"
            @cancel="templateModal=false"
            style="top:20px;"
            :destroyOnClose="true"
            okText="保存"
            cancelText="取消"
            @ok="uploadTemplate()"
            class="templateModal"
            :width="templateModalWidth+'px'"
            >
            <div class="templateModalBox">
                <ul class="site_ul">
                    <li>证书模板上传：
                        <a-upload
                        name="file"
                        :action="apiUrl+'manage/upload'"
                        :headers="headers"
                        @change="handleChange"
                        :showUploadList="false"
                        accept=".png"
                        >
                            <a-button style="position:absolute;top:0px;left:110px;"> {{imgSrc?'修改模板':'上传模板'}} </a-button>
                        </a-upload>
                        <span>（图片尺寸为1100*750）</span>
                    </li>
                    <li>设置姓名位置：<b ref="teacher" class="drag_box" v-drag style="width:100px;">张老师</b></li>
                    <li>设置证书编号位置：<b ref="certNum" class="drag_box certNum" v-drag>HNCDZSZ202000066</b> </li>
                    <li>设置身份证号位置：<b ref="idCardNum" class="drag_box idCardNum" v-drag>420000000000000000</b> </li>
                    <li>设置性别：<b ref="gender" class="drag_box gender" v-drag>男</b></li>
                    <li>设置证书姓名位置：<b ref="name" class="drag_box name" v-drag style="width:100px;">张老师</b> </li>
                    <li class="personPortrait">
                        设置头像位置：
                        <br>
                        <b ref="photo" class="drag_box" v-drag><img src="../../assets/person.jpg" alt=""></b>
                        <span class="secondSpan">（拖动预览）</span>
                    </li>

                    <li>设置有效期位置：<b ref="validDate" class="drag_box" v-drag style="width:150px;">YYYY-MM-DD</b></li>
                    <li>设置英文有效期位置：<b ref="validDateInEnglish" class="drag_box" v-drag style="width:150px;">Jan DD,YYYY</b> </li>
                    <li>设置活动开始日期位置：<b ref="startDate" class="drag_box" v-drag style="width:150px;">YYYY-MM-DD</b></li>
                    <li>设置活动结束日期位置：<b ref="endDate" class="drag_box" v-drag style="width:150px;">YYYY-MM-DD</b></li>
                    <li>设置开始日期英文位置：<b ref="startDateInEnglish" class="drag_box" v-drag style="width:150px;">Jan DD,YYYY</b></li>
                    <li>设置结束日期英文位置：<b ref="endDateInEnglish" class="drag_box" v-drag style="width:150px;">Jan DD,YYYY</b></li>
                    <li>设置签发日期位置：<b ref="signDate" class="drag_box" v-drag style="width:150px;">YYYY-MM-DD</b></li>
                    <li>设置签发日期英文位置：<b ref="signDateInEnglish" class="drag_box" v-drag style="width:150px;">Jan DD,YYYY</b></li>
                    <li>设置活动标题位置：<b ref="title" class="drag_box" v-drag style="width:150px;">活动标题</b></li>
                    <li>设置学时活动位置：
                        <a-input-number 
                            :min="1" 
                            :max="1000" 
                            @change="onChangeTrainingHour" 
                            style="margin-right:10px;width:150px"
                            placeholder="请输入学时"
                        />
                        <b ref="trainingHour" class="drag_box" v-drag>{{trainingHour}}</b> 
                    </li>
                </ul>
                <div class="template"  ref="template" :style="templateStyle">
                    <img v-if="imgSrc" ref="templateImg" :src="imgSrc" alt="">
                    <a-empty v-else description="暂无模板" class="empty"/>
                </div>
                <!-- <div class="page">
                    <a-pagination :total="20" v-model="current"/>
                </div> -->
            </div>
        </a-modal>
        <a-modal
            title="证书预览" 
            :visible="previewModal"
            @cancel="previewModal=false"
            style="top:20px;"
            :destroyOnClose="true"
            :footer="null"
            width="1000px"
            class="previewModal"
            >
                <img :src="previewUrl" alt="">
                <a-button type="primary" @click="downloadCert()">下载</a-button>
                <!-- <download 
                    :name="'下载'"
                    :upload="false"
                    :api="'certificate/download'"
                    fileName="证书.png"
                    :methods="'post'"
                    :formData="{'imgUrl':previewUrl}"
                    style="margin-top:20px;"
                ></download> -->
        </a-modal>
        <!-- 成绩录入 -->
        <a-modal
            style="text-align:center"
            :destroyOnClose='true'
            :footer="null"
            :visible="openAddPaperBox"
            title = "成绩录入"
            @cancel="openAddPaperBox=false"
            >
                <div class="upload">
                    <p><a-icon type="exclamation-circle" />上传前请先下载模板，按照模板要求将内容录入到模板中<br>模板的表头名称不能更改，表头行不能删除</p>
                    <img src="../../assets/load_exer.png" alt="">
                    <p>支持格式：xls、xlsx</p>
                    <download 
                        :name="'下载模板'"
                        :api="info=='onePlusExam'?'common/oneplusXRecordTemplate':'manage/record/downloadTemplate'"
                        :fileName="'录入成绩模板.xls'"
                        :isPrimary="false"
                    ></download>
                    <br>
                    <a-upload
                        :fileList="fileList"
                        :remove="handleRemove"
                        :beforeUpload="beforeUpload"
                        accept='.xls,.xlsx'
                        >
                        <a-button style='margin-top:20px;'>
                             选择文件
                        </a-button>
                        </a-upload>
                        <a-button
                        type="primary"
                        @click="handleUpload"
                        :disabled="fileList.length === 0"
                        :loading="uploading"
                        style="margin-top: 16px"
                        >
                        {{uploading ? '上传中' : '开始上传' }}
                        </a-button>
                </div>
        </a-modal>
        <!-- 修改成绩模板 -->
        <a-modal
            :destroyOnClose='true'
            okText="确认"
            cancelText="取消"
            :visible="editRecordBox"
            title = "修改"
            @ok="submitEditData()"
            @cancel="editRecordBox=false"
            >
            <eform
                :formData="formData"
                class="form"
                ref="form"
                :fields="fields"
                
            ></eform>
        </a-modal>
    </div>
</template>
<script>
import confirmBox from "@/components/common/confirmBox"
import selectDate from "@/components/common/selectDate"
import eform from "@/components/common/form"
const columns=[
    {
        title: '序号',
        dataIndex: 'index',
        width:70
    },{
        title: '真实姓名',
        dataIndex: 'realname',
        width:100
    },{
        title: '性别',
        dataIndex: 'gender',
        width:70
    },{
        title: '用户名',
        dataIndex: 'name',
    },{
        title: '账号',
        dataIndex: 'account',
    },{
        title: '手机号',
        dataIndex: 'telephone',
    },{
        title: '身份证号',
        dataIndex: 'idCardNum',
    },{
        title: '所属单位',
        dataIndex: 'instituteName',
    },{
        title: '所属课程',
        dataIndex: 'courseTitle',
    },{
        title: '证书编号',
        dataIndex: 'certNum',
    },{
        title: '成绩',
        scopedSlots: { customRender: 'score' },
        width:150
    },{
        title: '是否合格',
        scopedSlots: { customRender: 'passed' },
    },{
        title: '考试时间',
        dataIndex: 'createTime',
    },{
        title: '操作',
        scopedSlots: { customRender: 'action' },
    }
]
import download from "@/components/common/download"
import axios from "axios"
import {
    getCertListApi,
    deleteCertApi,
    generateCourseCertApi,
    uploadTemplateApi,
    generateTrainingTemplateApi,
    updateTemplateApi,
    onePlusRecordListApi,
    generateExamCertApi,
    deleteOnePlusCertApi,
    deleteRecordApi,
    deleteOnePlusRecordApi,
    recordUpdateApi,
    resetRecordApi
} from "@/request/api"
import innerCommon from "@/components/common/innerCommon"
import JsPDF from 'jspdf'
export default {
    name:'certManager',
    components:{innerCommon,selectDate,confirmBox,download,eform},
    props:{
        type:Number,//0是成绩  1是培训
        location:Array,
        info:String,//判断是否是1+X模块
        activityId:String,//考试/培训的id
        activeType:Number,//导入模板时判断身份
    },
    created(){
        this.searchInfo.courseId=this.$route.query.id
        this.init()
        if(this.info=='onePlusExam'&&this.type==0){
            this.columns[8]={
                title: '考试名称',
                dataIndex: 'examName',
            }
        }        
    },
    data(){
        let validateIdNumber=(rule,value,callback)=>{
            let reg=/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if(!value||reg.test(value)){
                callback()
            }else{
                callback(new Error('请输入正确的身份证号'))
            }
        }
        let validateName=(rule,value,callback)=>{
            if(value){
                if(value.trim().length === 0){
                    callback(new Error('姓名不能全是空格'))
                }else if(value.length>6){
                    callback(new Error('姓名长度不能超过6'))
                }else{
                    callback()
                }
            }else{
                callback()
            }
        }
        let validateIdScore=(rule,value,callback)=>{
            let reg=/^\d{1,}$/
            if(!value||reg.test(value)){
                callback()
            }else{
                callback('请输入数字')
            }
        }
        let formData=[
            {
                label:"真实姓名",
                prop:"realname",
                placeholder:'请输入真实姓名',
                rules:[{required:true,message:'请输入真实姓名'},{validator:validateName}],
            },{
                label:"身份证号",
                prop:"idCardNum",
                placeholder:'请输入身份证号',
                rules:[{required:true,message:'请输入身份证号'},{validator:validateIdNumber}],
            },{
                label:"理论成绩",
                prop:"theoryScore",
                placeholder:'请输入理论成绩',
                rules:[{required:false,message:'请输入理论成绩'},{validator:validateIdScore}],
            },{
                label:"实操成绩",
                prop:"operationScore",
                placeholder:'请输入实操成绩',
                rules:[{required:false,message:'请输入实操成绩'},{validator:validateIdScore}],
            },{
                label:"理论合格分",
                prop:"theoryPassScore",
                placeholder:'请输入理论合格分',
                rules:[{required:false,message:'请输入理论合格分'},{validator:validateIdScore}],
            },{
                label:"实操合格分",
                prop:"operationPassScore",
                placeholder:'请输入实操合格分',
                rules:[{required:false,message:'请输入实操合格分'},{validator:validateIdScore}],
            }
        ]
        return{
            delBtn:false,
            clickFlag:false,
            formData,
            list:[],
            columns,
            pagination:{pageSize:10,total:0,current:1},
            searchInfo:{
                pageSize:10,
                page:1,
                courseId:'',
                keyword:'',
                startTime:'',
                endTime:''
            },
            templateModal:false,
            imgSrc:'',
            apiUrl:window.g.apiUrl,
            headers: {
                authorization: 'authorization-text',
            },
            element:null,
            previewModal:false,
            previewUrl:'',
            position:{
                setWidth:0,
                setHeight:0
            },
            file:null,
            openAddPaperBox:false,
            fileList:[],
            uploading:false,
            templateStyle:'',//模板的宽度
            templateModalWidth:1600,//模板弹出框的宽度\
            siteInfo:null,
            current:1,
            trainingHour:1,
            name:'',
            editRecordBox:false,
            fields:undefined,
            recordId:undefined,
            certId:'',
            selectedRowKeys:[],
            selectedRows:[],
        }
    },
    directives: {
        drag: (el)=>{
            let dragBox = el; //获取当前元素
            let left
            let top
            dragBox.onmousedown = e => {
                //算出鼠标相对元素的位置
                let disX = e.clientX - dragBox.offsetLeft;
                let disY = e.clientY - dragBox.offsetTop;
                document.onmousemove = e => {
                    //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
                    left = e.clientX - disX;
                    top = e.clientY - disY;
                    //移动当前元素
                    dragBox.style.left = left + "px";
                    dragBox.style.top = top + "px";
                };
                document.onmouseup = () => {
                    //鼠标弹起来的时候不再移动
                    document.onmousemove = null;
                    //预防鼠标弹起来后还会循环（即预防鼠标放上去的时候还会移动）  
                    document.onmouseup = null;
                };
            };
        }
    },
    methods:{
        init(){
            if(this.type==1){
                this.columns=this.columns.filter(item=>item.dataIndex!='courseTitle')
            }
            let api
            let formData
            if(this.info=='onePlusExam'){
                api=onePlusRecordListApi
                formData={...this.searchInfo,'type':this.type,'activityId':this.activityId}
                
            }else{
                api=getCertListApi
                formData={...this.searchInfo,'type':this.type}
            }
            this.getToken(api,formData,res=>{
                this.list=res.data.rows.map((item,index)=>({
                    ...item,
                    ...item.owner,
                    'index':(this.searchInfo.page-1)*10+index+1,
                    'courseTitle':item.course&&item.course.title,
                    'id':item.id,
                    'examType':item.course&&item.course.chapters[0].tasks[0].examType,
                    'certNum':item.certificate&&item.certificate.certNum
                }))
                if(this.info=='onePlusExam'){
                    if(this.type==0){
                        this.list=this.list.map(item=>({...item,'examTime':item.onePlusXExam.activityStart+'-'+item.onePlusXExam.activityEnd}))
                        this.list=this.list.map(item=>({...item,'examName':item.onePlusXExam.title}))
                    }else{
                        this.list=this.list.map(item=>({...item,'examTime':item.onePlusXTraining.activityStart+'-'+item.onePlusXTraining.activityEnd}))
                    }
                }
                this.pagination.total=res.data.count;
                this.imgSrc=res.data.rows[0].certTemplate
                // console.log(this.list)
                // this.list.filter((item,index)=>{
                //      if(item.certificate.id){
                //          this.delBtn=true
                //      }else{
                //          this.delBtn=false
                //      }
                // })

                if(this.imgSrc){
                    let info=res.data.rows[0]
                    this.siteInfo=
                        {
                            'teacher':{'left':info.setWidth,'top':info.setHeight},
                            'other':info.coordinate
                        }
                }
            })
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
        },
        //全选
        // checkAll($event){
        //     if($event.target.checked){
        //         this.selectedRowKeys=this.list.map((item)=>item.id);
        //         this.selectedRows=this.list
        //     }else{
        //         this.selectedRowKeys=[];
        //         this.selectedRows=[];
        //     }
        // },
        //批量删除成绩
         batchDelResult(){
             if(this.selectedRowKeys.length<=0){
                this.$message.warning("请先选择要删除的成绩！")
                return
            }
            this.$confirm({
            title: "确定删除吗？",
            cancelText: "取消",
            okText: "确定",
            onOk: () => {
            let idArr=[]
                this.selectedRowKeys.forEach((item) => {
                    idArr.push(item)
                });
            this.getToken(deleteOnePlusRecordApi, {'type':1,'recordId':idArr}, (res) => {
                if (res.code == 200) {
                    this.$message.success("删除成功");
                    this.selectedRowKeys = [];
                    this.init()
                }
            });
        },
        onCancel() {},
         });
         },
        //批量删除证书
        batchDelCert(){
            if(this.selectedRowKeys.length<=0){
                this.$message.warning("请先选择要删除的证书！")
                return
            }
            this.$confirm({
            title: "确定删除吗？",
            cancelText: "取消",
            okText: "确定",
            onOk: () => {
            let api
            let formData
            let IdArr=[]
            this.selectedRowKeys.forEach((item)=>{
                if(this.list.filter((value)=>value.id == item).length>0){
                        IdArr.push(this.list.filter((value) => value.id == item)[0].certificate.id);
                    }
                })
            if(this.info=='onePlusExam'){
                api=deleteOnePlusCertApi
                formData={'certId':IdArr}
            }else{
                api=deleteCertApi
                formData={'recordId':IdArr}
            }
            this.getToken(api,formData,res=>{
                this.$message.success(res.message)
                this.selectedRowKeys=[]
                this.init()
                 })
              },
            onCancel() {},
             });
        },
        changePage(data){
            this.searchInfo.page=data.current
            this.pagination.current=data.current
            this.init()
        },
        onSearch(data){
            this.searchInfo.keyword=data
            this.pagination.current=1
            this.searchInfo.page=1
            this.init()
        },
        returnBack(){
            this.$emit("returnBack")
            // this.$router.go(-1)
        },
        openTemplate(){
            this.templateModal=true
            if(this.imgSrc){//路径不为空，就说明有模板
                this.$nextTick(()=>{
                    this.$refs.teacher.style.left=this.siteInfo.teacher.left?this.siteInfo.teacher.left+400+'px':undefined
                    this.$refs.teacher.style.top=this.siteInfo.teacher.top?this.siteInfo.teacher.top-10+'px':undefined
                    if(this.siteInfo.other.idCardNum){
                        this.$refs.idCardNum.style.left=this.siteInfo.other.idCardNum[0]+400+'px'
                        this.$refs.idCardNum.style.top=this.siteInfo.other.idCardNum[1]-10+'px'
                    }
                    if(this.siteInfo.other.certNum){
                        this.$refs.certNum.style.left=this.siteInfo.other.certNum[0]+400+'px'
                        this.$refs.certNum.style.top=this.siteInfo.other.certNum[1]-10+'px'
                    }
                    if(this.siteInfo.other.photo){
                        this.$refs.photo.style.left=this.siteInfo.other.photo[0]+420+'px'
                        this.$refs.photo.style.top=this.siteInfo.other.photo[1]+'px'
                    }
                    if(this.siteInfo.other.name){
                        this.$refs.name.style.left=this.siteInfo.other.name[0]+405+'px'
                        this.$refs.name.style.top=this.siteInfo.other.name[1]-7+'px'
                    }
                    if(this.siteInfo.other.gender){
                        this.$refs.gender.style.left=this.siteInfo.other.gender[0]+400+'px'
                        this.$refs.gender.style.top=this.siteInfo.other.gender[1]-10+'px'
                    }  
                    if(this.siteInfo.other.validDate){
                        this.$refs.validDate.style.left=this.siteInfo.other.validDate[0]+400+'px'
                        this.$refs.validDate.style.top=this.siteInfo.other.validDate[1]-5+'px'
                    }  
                    if(this.siteInfo.other.validDateInEnglish){
                        this.$refs.validDateInEnglish.style.left=this.siteInfo.other.validDateInEnglish[0]+400+'px'
                        this.$refs.validDateInEnglish.style.top=this.siteInfo.other.validDateInEnglish[1]-5+'px'
                    } 
                    if(this.siteInfo.other.startDate){
                        this.$refs.startDate.style.left=this.siteInfo.other.startDate[0]+400+'px'
                        this.$refs.startDate.style.top=this.siteInfo.other.startDate[1]-5+'px'
                    } 
                    if(this.siteInfo.other.endDate){
                        this.$refs.endDate.style.left=this.siteInfo.other.endDate[0]+400+'px'
                        this.$refs.endDate.style.top=this.siteInfo.other.endDate[1]-5+'px'
                    } 
                    if(this.siteInfo.other.startDateInEnglish){
                        this.$refs.startDateInEnglish.style.left=this.siteInfo.other.startDateInEnglish[0]+400+'px'
                        this.$refs.startDateInEnglish.style.top=this.siteInfo.other.startDateInEnglish[1]-5+'px'
                    } 
                    if(this.siteInfo.other.endDateInEnglish){
                        this.$refs.endDateInEnglish.style.left=this.siteInfo.other.endDateInEnglish[0]+400+'px'
                        this.$refs.endDateInEnglish.style.top=this.siteInfo.other.endDateInEnglish[1]-5+'px'
                    }
                    if(this.siteInfo.other.signDate){
                        this.$refs.signDate.style.left=this.siteInfo.other.signDate[0]+400+'px'
                        this.$refs.signDate.style.top=this.siteInfo.other.signDate[1]-5+'px'
                    }
                    if(this.siteInfo.other.signDateInEnglish){
                        this.$refs.signDateInEnglish.style.left=this.siteInfo.other.signDateInEnglish[0]+400+'px'
                        this.$refs.signDateInEnglish.style.top=this.siteInfo.other.signDateInEnglish[1]-5+'px'
                    }
                    if(this.siteInfo.other.title){
                        this.$refs.title.style.left=this.siteInfo.other.title[0]+400+'px'
                        this.$refs.title.style.top=this.siteInfo.other.title[1]-5+'px'
                    }
                    if(this.siteInfo.other.title){
                        this.$refs.title.style.left=this.siteInfo.other.title[0]+400+'px'
                        this.$refs.title.style.top=this.siteInfo.other.title[1]-5+'px'
                    }
                    if(this.siteInfo.other.trainingHour.coordinate){
                        this.$refs.trainingHour.style.left=this.siteInfo.other.trainingHour.coordinate[0]+400+'px'
                        this.$refs.trainingHour.style.top=this.siteInfo.other.trainingHour.coordinate[1]-5+'px'
                        this.trainingHour=this.siteInfo.other.trainingHour.value
                    }
                })
            }
        },
        handleChange(info) {
            if (info.file.status === 'done') {
                this.file=info.file.originFileObj
                this.imgSrc=info.fileList[info.fileList.length-1].response.data.imgUrl[0]
                this.$message.success(`${info.file.name} 上传成功`);
                setTimeout(() => {
                    this.getWidth()
                }, 500);
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} 上传失败`);
            }
        },
        getWidth(){
            this.templateModalWidth=this.$refs.templateImg.clientWidth+500
        },
        previewCert(data,name){
            this.previewModal=true
            this.previewUrl=data
            this.name=name
        },
        // 删除证书
        deleteCert(data){
            let api
            let formData
            if(this.info=='onePlusExam'){
                api=deleteOnePlusCertApi
                formData={'certId':data.certificate.id}
            }else{
                api=deleteCertApi
                formData={'recordId':data.certificate.id}
            }
            this.getToken(api,formData,res=>{
                this.$message.success(res.message)
                this.init()
            })
        },
        // 删除成绩
        deleteRecord(data){
            let api
            let formData
            if(this.info=='onePlusExam'){
                api=deleteOnePlusRecordApi
                formData={'recordId':data.id,'type':1}
            }else{
                api=deleteRecordApi
                formData={'recordId':data.id,'type':0}
            }
            this.getToken(api,formData,res=>{
                this.$message.success(res.message)
                this.init()
            })
        },
        //生成证书
        generateCourseCert(id){
            this.clickFlag=true
            if(this.info=='onePlusExam'){
                this.getToken(generateExamCertApi,{'recordId':id||null,'activityId':this.activityId,'type':this.type},res=>{
                    if(res.code===200){
                        this.clickFlag=false
                    }
                    this.$message.success(res.message)
                    this.init()
                })
            }else{
                if(this.type==0){
                    this.getToken(generateCourseCertApi,{'recordId':id||null,'courseId':this.searchInfo.courseId},res=>{
                        if(res.code===200){
                            this.clickFlag=false
                         }
                        this.$message.success(res.message)
                        this.init()
                    })
                }else{
                    this.getToken(generateTrainingTemplateApi,{'recordId':id||null,'classId':this.searchInfo.courseId},res=>{
                        if(res.code===200){
                             this.clickFlag=false
                         }
                        this.$message.success(res.message)
                        this.init()
                    })
                }
            }
        },
        uploadTemplate(){
            if(!this.imgSrc){
                this.$message.error('请上传证书模板')
                return
            }
            let left=(parseInt(this.$refs.teacher.style.left)-400)
            let top=(parseInt(this.$refs.teacher.style.top)+10)
            let coordinate=
                {
                    'idCardNum':this.$refs.idCardNum.style.left?[parseInt(this.$refs.idCardNum.style.left)-400,parseInt(this.$refs.idCardNum.style.top)+10]:undefined,
                    'certNum':this.$refs.certNum.style.left?[parseInt(this.$refs.certNum.style.left)-400,parseInt(this.$refs.certNum.style.top)+10]:undefined,
                    'photo':this.$refs.photo.style.left?[parseInt(this.$refs.photo.style.left)-420,parseInt(this.$refs.photo.style.top)]:undefined,
                    'name':this.$refs.name.style.left?[parseInt(this.$refs.name.style.left)-405,parseInt(this.$refs.name.style.top)+7]:undefined,
                    'gender':this.$refs.gender.style.left?[parseInt(this.$refs.gender.style.left)-400,parseInt(this.$refs.gender.style.top)+10]:undefined,
                    'validDate':this.$refs.validDate.style.left?[parseInt(this.$refs.validDate.style.left)-400,parseInt(this.$refs.validDate.style.top)+5]:undefined,
                    'validDateInEnglish':this.$refs.validDateInEnglish.style.left?[parseInt(this.$refs.validDateInEnglish.style.left)-400,parseInt(this.$refs.validDateInEnglish.style.top)+5]:undefined,
                    'startDate':this.$refs.startDate.style.left?[parseInt(this.$refs.startDate.style.left)-400,parseInt(this.$refs.startDate.style.top)+5]:undefined,
                    'endDate':this.$refs.endDate.style.left?[parseInt(this.$refs.endDate.style.left)-400,parseInt(this.$refs.endDate.style.top)+5]:undefined,
                    'startDateInEnglish':this.$refs.startDateInEnglish.style.left?[parseInt(this.$refs.startDateInEnglish.style.left)-400,parseInt(this.$refs.startDateInEnglish.style.top)+5]:undefined,
                    'endDateInEnglish':this.$refs.endDateInEnglish.style.left?[parseInt(this.$refs.endDateInEnglish.style.left)-400,parseInt(this.$refs.endDateInEnglish.style.top)+5]:undefined,
                    'signDate':this.$refs.signDate.style.left?[parseInt(this.$refs.signDate.style.left)-400,parseInt(this.$refs.signDate.style.top)+5]:undefined,
                    'signDateInEnglish':this.$refs.signDateInEnglish.style.left?[parseInt(this.$refs.signDateInEnglish.style.left)-400,parseInt(this.$refs.signDateInEnglish.style.top)+5]:undefined,
                    'title':this.$refs.title.style.left?[parseInt(this.$refs.title.style.left)-400,parseInt(this.$refs.title.style.top)+5]:undefined,
                    'trainingHour':{'coordinate':this.$refs.trainingHour.style.left?[parseInt(this.$refs.trainingHour.style.left)-400,parseInt(this.$refs.trainingHour.style.top)+5]:undefined,'value':this.trainingHour},
               }
            if(this.$refs.idCardNum.style.left||this.$refs.teacher.style.left||this.$refs.certNum.style.left||this.$refs.photo.style.left||this.$refs.name.style.left||this.$refs.gender.style.left||this.$refs.idCardNum.style.top||this.$refs.teacher.style.top||this.$refs.certNum.style.top||this.$refs.photo.style.top||this.$refs.name.style.top||this.$refs.gender.style.top){
                if(!this.$refs.teacher.style.left){
                    this.$message.error('姓名位置不能为空')
                    return
                }
                let formData=new FormData()
                formData.append('courseId',this.searchInfo.courseId)
                formData.append('setWidth',left)
                formData.append('setHeight',top)
                formData.append('type',this.info=='onePlusExam'?(this.type==0?2:3):this.type)
                formData.append('coordinate',JSON.stringify(coordinate))
                formData.append('file',this.file)
                let api
                let params
                if(this.file){
                    api=uploadTemplateApi
                    params=formData
                }else{
                    api=updateTemplateApi
                    params={
                        'type':this.info=='onePlusExam'?(this.type==0?2:3):this.type,
                        'setHeight':top,
                        'setWidth':left,
                        'courseId':this.searchInfo.courseId,
                        'coordinate':JSON.stringify(coordinate)
                    }
                }
                this.getToken(api,params,res=>{
                    this.$message.success(res.message)
                    this.templateModal=false
                    this.init()
                })
            }else{
                this.$message.error('设置的位置不能为空')
                return
            }
            
        },
        changTime(start,end){
            this.searchInfo.startTime=start
            this.searchInfo.endTime=end
            this.searchInfo.page=1
            this.pagination.current=1
            this.init()
        },
        // 成绩录入
        openUploadBox(){
            this.openAddPaperBox=true
        },
        handleRemove(file) {
            const index = this.fileList.indexOf(file);
            const newFileList = this.fileList.slice();
            newFileList.splice(index, 1);
            this.fileList = newFileList
        },
        beforeUpload(file) {
            this.fileList = [file]
            return false;
        },
        handleUpload() {
            const { fileList } = this;
            const formData = new FormData();
            let api=''
            if(this.info=='onePlusExam'){
                formData.append('activityId',this.activityId)
                formData.append('type',this.activeType)
                api='manage/onePlusXRecord/importRecord'
            }else{
                api='manage/record/importTrainingRecord'
                formData.append('classId', this.searchInfo.courseId);
            }   
            fileList.forEach((file) => {
                formData.append('file', file);
            });
            this.uploading = true
            // You can use any AJAX library you like
            axios.post(window.g.apiUrl+api,formData).then(res=>{
                this.fileList = []
                this.uploading = false
                if(res.data.code==200){
                    this.$message.success(res.data.message)
                    this.init()
                }else{
                    this.$message.error(res.data.message)
                }
                this.openAddPaperBox=false
            }).catch(()=>{
                this.uploading = false
                this.$message.error('上传失败');
            });
        },
        // 更改学时
        onChangeTrainingHour(data){
            this.trainingHour=data
        },
        // 下载证书
        downloadCert(){
            let PDF = new JsPDF('p', 'pt', 'a4')
            PDF.addImage(this.previewUrl,'png',0,0,550,370)
            PDF.save(this.name+'的证书.pdf')
        },
        editRecord(data){
            this.fields=data
            this.editRecordBox=true
            this.recordId=data.id
            if(data.theoryScore){
                this.formData[2].rules[0].required=true
                this.formData[4].rules[0].required=true
            }else{
                this.formData[2].rules[0].required=false
                this.formData[4].rules[0].required=false
            }
            if(data.operationScore){
                this.formData[3].rules[0].required=true
                this.formData[5].rules[0].required=true
            }else{
                this.formData[3].rules[0].required=false
                this.formData[5].rules[0].required=false
            }
        },
        submitEditData(){
            this.$refs.form.form.validateFields().then(res=>{
                let formData={...res,'recordId':this.recordId,'type':this.info=='onePlusExam'?1:0}
                if(res.theoryScore&&!res.operationScore){
                    if(res.theoryScore>=res.theoryPassScore){
                        formData.passed=1
                    }else{
                        formData.passed=0
                    }
                }else if(!res.theoryScore&&res.operationScore){
                    if(res.operationScore>=res.operationPassScore){
                        formData.passed=1
                    }else{
                        formData.passed=0
                    }
                }else if(res.theoryScore&&res.operationScore){
                    if(res.operationScore>=res.operationPassScore&&res.theoryScore>=res.theoryPassScore){
                        formData.passed=1
                    }else{
                        formData.passed=0
                    }
                }
                this.getToken(recordUpdateApi,formData,data=>{
                    this.$message.success(data.message)
                    this.editRecordBox=false
                    this.init()
                })
            })
        },
        // 重新考试
        reviewTest(id,name){
            this.$confirm({
                title: '确定让用户'+name+'重新考试吗？',
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    this.getToken(resetRecordApi,{'recordId':id},res=>{
                        this.$message.success(res.message);
                        this.init()
                    })
                },
                onCancel() {
                },
            });
        }
    }
}
</script>
<style lang="stylus">
.previewModal
    .ant-modal-body
        text-align:center
        img
            max-width:100%
            margin:0 auto
</style>
<style lang="stylus">
.templateModal
    .ant-modal-body
        padding-top:6px;
    .templateModalBox
        display:flex;
        ul.site_ul
            list-style:none;
            margin-bottom:0;
            position:relative;
            border-left:1px solid #ddd;
            border-top:1px solid #ddd;
            padding:0;
            width:400px;
            li
                line-height:35px;
                border-right:1px solid #ddd;
                border-bottom:1px solid #ddd;
                padding:0 10px;
                b
                    font-size:20px;
                    display:inline-block
                    text-align:center;
                    cursor:pointer
                    position:absolute
                span 
                    margin-left:10px;
                    color:#999;
                    float:right;
                .secondSpan
                    margin-left:10px;
                .drag_box
                    font-size:20px;
                    font-family:'KaiTi'
            li.personPortrait
                height:220px;
                img 
                    width:132px;
                    height:166px;
                    
        .template
            border:1px solid #ddd;
            min-height:500px;
            margin-left:24px;
            .empty
                position:relative;
                top:200px;
                    
</style>